import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入login组件
import Login from '@/views/Login.vue'
// 导入HOme组件
import Home from '@/views/Home.vue'
// 导入Users组件
import Users from '@/views/user/Users.vue'
// 导入Rights组件
import Rights from '@/views/power/Rights.vue'
// 导入Roles组件
import Roles from '@/views/power/Roles.vue'
// 导入Cate组件
import Cate from '@/views/goods/Cate.vue'
// 导入Params组件
import Params from '@/views/goods/Params.vue'
// 导入list组件
import List from '@/views/goods/List.vue'
// 导入add组件
import Add from '@/views/goods/Add.vue'
// 导入order组件
import Order from '@/views/order/Order.vue'
// 导入Report组件
import Report from '@/views/reports/Report.vue'

Vue.use(VueRouter)

const routes = [
  // 路由重定向
  { path: '/', redirect: '/login' },
  // 登录页面路由规则
  { path: '/login', component: Login },
  // 主页的路由规则
  {
    path: '/home',
    component: Home,
    // 子路由重定向,重定向到users页面
    redirect: '/home/users',
    // 主页子路由
    // 用户列表Users页面的路由规则
    children: [
      { path: 'users', component: Users },
      { path: 'rights', component: Rights },
      { path: 'roles', component: Roles },
      { path: 'categories', component: Cate },
      { path: 'params', component: Params },
      { path: 'goods', component: List },
      { path: 'goods/add', component: Add },
      { path: 'orders', component: Order },
      { path: 'reports', component: Report }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫控制访问权限
router.beforeEach((to, from, next) => {
  // 如果要跳转的页面是login，直接放行
  if (to.path === '/login') return next()
  // 如果访问的不是login页面，则从sessionStorage中获取token
  // 如果sessionStorage中有token则放行，没有则跳转到login页面
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
